﻿using System;
using System.IO;
using System.Linq;
using FileHelpers;
using Model;
using Model.Static;

namespace Command.Commands
{
	public class SyncAchievementCategoriesCommand : BaseCommand<Options>
	{
		private readonly IRepository _repository;

		public SyncAchievementCategoriesCommand(IRepository repository)
		{
			_repository = repository;
		}

		protected override void InternalExecute(Options options)
		{
			var file = Path.Combine(Environment.CurrentDirectory, "Static\\Data\\AchievementCategory.csv");
			var records = new FileHelperEngine<AchievementCategoryRecord> {Options = {IgnoreFirstLines = 1}}
				.ReadFile(file)
				.OrderBy(x => x.ExternalParentKey)
				.ThenBy(x => x.ExternalKey)
				.ToArray();
			foreach (var record in records)
			{
				var theRecord = record;
				var category = _repository.Query<AchievementCategory>().FirstOrDefault(x => x.ExternalKey == theRecord.ExternalKey);
				if (category == null)
				{
					category = new AchievementCategory
					{
						ExternalKey = theRecord.ExternalKey,
						Name = theRecord.Name,
						Parent = _repository.Query<AchievementCategory>().FirstOrDefault(x => x.ExternalKey == theRecord.ExternalParentKey)
					};
					Console.WriteLine("Creating Missing Category: {0}", category.ExternalKey);
					_repository.Save(category);
				}
			}
		}
	}
}
